package cn.com.digitalnet.ad.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * cookie工具类，解决servlet3.0以前不能添加httpOnly属性的问题
 * 
 * @author zhang-long
 * @createTime 2013-6-20
 */
public class CookieUtil {

	/**
	 * @param response
	 *            HttpServletResponse类型的响应
	 * @param cookie
	 *            要设置httpOnly的cookie对象
	 */
	public static void addHttpOnlyCookie(HttpServletResponse response,
			Cookie cookie) {
		// 判断对象是否存在null的情况
		if (checkObjIsNull(response) || checkObjIsNull(cookie)) {
			return;
		}

		// 依次取得cookie中的名称、值、最大生存时间、路径、域和是否为安全协议信息
		String cookieName = cookie.getName();
		String cookieValue = cookie.getValue();
		int maxAge = cookie.getMaxAge();
		String path = cookie.getPath();
		String domain = cookie.getDomain();
		boolean isSecure = cookie.getSecure();

		StringBuffer strBufferCookie = new StringBuffer();
		strBufferCookie.append(cookieName + "=" + cookieValue + ";");

		if (maxAge >= 0) {
			strBufferCookie.append("Max-Age=" + cookie.getMaxAge() + ";");
		}

		if (!checkObjIsNull(domain)) {
			strBufferCookie.append("domain=" + domain + ";");
		}

		if (!checkObjIsNull(path)) {
			strBufferCookie.append("path=" + path + ";");
		}

		if (isSecure) {
			strBufferCookie.append("secure;HTTPOnly;");
		} else {
			strBufferCookie.append("HTTPOnly;");
		}

		response.addHeader("Set-Cookie", strBufferCookie.toString());
	}

	private static boolean checkObjIsNull(Object obj) {
		if (obj == null) {
			return true;
		}
		return false;
	}

}